import { Component, PureComponent, createContext } from "react";

//1.
const UserContext = createContext({
  nickName: "默认",
  level: -1,
  region: 'China'
})

class Home extends PureComponent {
  render() {
    return (
      <UserContext.Consumer>
        {
          user => <h2>{`姓名：${user.nickName} 等级：${user.level} 地区：${user.region}`}</h2>
        }
      </UserContext.Consumer>
    )
  }
}

class About extends PureComponent {
  render() {
    return (
      // 3. 这样写就导致每个组件就需要写一次 UserContext.Consumer
      <UserContext.Consumer>
        {
          user => <h2>{`姓名：${user.nickName} 等级：${user.level} 地区：${user.region}`}</h2>
        }
      </UserContext.Consumer>
    )
  }
}

class Detail extends PureComponent {
  render() {
    return (
      <UserContext.Consumer>
        {
          user => (
            <ul>
              <li>{user.nickName}</li>
              <li>{user.level}</li>
              <li>{user.region}</li>
            </ul>
          )
        }
      </UserContext.Consumer>
    )
  }
}

class App extends Component {
  render() {
    return (
      <div>
        {/* 2. */}
        <UserContext.Provider value={{nickName: 'yzh', level: 999, region: '中国'}}>
          <Home />
          <About />
        </UserContext.Provider>

        <Detail />
      </div>
    )
  }
}

export default App